<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="show"
      @close="reset"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼盘名称" prop="estateName">
          <el-input
            v-model="form.estateName"
            placeholder="请输入名称"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="分布类型" prop="estateType">
          <el-select v-model="form.estateType" placeholder="分布类型" clearable>
            <el-option
              v-for="dict in dict.type.dict_estate_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <!-- v-if 解决回显不动态拉取接口问题 -->
          <el-cascader
            v-if="show"
            ref="areaPicker"
            v-model="form.region"
            :props="areaProps"
            :show-all-levels="false"
            @change="handleChangeArea"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="经纬度" prop="longitude">
          <el-input
            v-model="form.longitude"
            placeholder="点击坐标拾取"
            disabled
            style="width: 120px"
          />
          <el-input
            v-model="form.latitude"
            placeholder="点击坐标拾取"
            disabled
            style="width: 120px; margin: 0 6px"
          />
          <el-button icon="el-icon-map-location" @click="handleLocation"
          >坐标拾取
          </el-button
          >
        </el-form-item>
        <el-form-item label="具体地址" prop="premisesAddress">
          <el-input
            v-model="form.premisesAddress"
            style="width: 240px"
            placeholder="请输入具体地址"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!-- 地图位置拾取器 -->
      <el-dialog
        :visible.sync="locationDialog"
        title="选择经纬度"
        width="1200px"
        :destroy-on-close="true"
        append-to-body
      >
        <location :city="cityName" @selectLocation="selectLocation" ref="location" :lat="form.latitude"
                  :lng="form.longitude"
        ></location>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import { listArea } from '@/api/system/config'
import location from '@/components/location/location.vue'
import { debounce } from '@/utils'
import { addEstate, editEstate } from '@/api/house/estate'

export default {
  name: 'add',
  components: { location },
  dicts: ['dict_estate_type'],
  props: {
    title: {
      type: String,
      default: '新增楼盘'
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      //定位城市名
      cityName: '',
      locationDialog: false, //坐标弹窗
      region: [],
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 4
              }))
              resolve(areas)
            }
          )
        }
      },
      // 表单参数
      form: {
        estateType: '', //楼盘分布类型：1.集中式；2.分散式
        estateName: '', //楼盘名称
        provinceId: '', //省
        cityId: '', //市
        districtId: '', //区
        streetId: '', //所属街道
        communityId: '', //所属社区
        premisesAddress: '', //小区地址
        propertyId: null, //物业id
        propertyName: '', //物业名称
        longitude: null, //经度
        latitude: null, //纬度
        region: []
      },
      // 表单校验
      rules: {
        estateName: [
          { required: true, message: '楼盘名称不能为空', trigger: 'blur' }
        ],
        estateType: [
          { required: true, message: '分布类型不能为空', trigger: 'blur' }
        ],
        region: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
        longitude: [
          { required: true, message: '经纬度不能为空', trigger: 'blur' }
        ],
        premisesAddress: [
          { required: true, message: '具体地址不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    show: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.init()
      }
    },
    "form.region"(newVal, oldVal) {
      this.form.provinceId = newVal[0];
      this.form.cityId = newVal[1];
      this.form.districtId = newVal[2];
      this.form.streetId = newVal[3];
      this.form.communityId = newVal[4];
    },
  },
  methods: {
    init() {
      this.reset()
      if (this.data && this.data.estateId) {
        this.form = JSON.parse(JSON.stringify(this.data))
      }
    },
    // 表单重置
    reset() {
      this.form = {
        estateType: '', //楼盘分布类型：1.集中式；2.分散式
        estateName: '', //楼盘名称
        provinceId: '', //省
        cityId: '', //市
        districtId: '', //区
        streetId: '', //所属街道
        communityId: '', //所属社区
        premisesAddress: '', //小区地址
        propertyId: '', //物业id
        propertyName: '', //物业名称
        longitude: null, //经度
        latitude: null, //纬度
        region: []
      }
      this.resetForm('form')
      this.cityName = ''
    },
    //区域选择
    handleChangeArea(val) {
      const checkedNode = this.$refs['areaPicker'].panel.getNodeByValue(val)
      const ids = checkedNode.path
      const labels = checkedNode.pathLabels
      console.log('handleChangeArea',ids, labels)
      if (labels[1] == '市辖区') {
        this.cityName = labels[0]
      } else {
        this.cityName = labels[1]
      }
      this.form.provinceName = labels[0]
      this.form.cityName = labels[1]
      this.form.districtName = labels[2]
      this.form.streetName = labels[3]
      this.form.communityName = labels[4]
      //console.log(this.cityName);
    },
    //坐标拾取
    handleLocation() {
      this.locationDialog = true
      this.$nextTick(() => {
        this.$refs['location'].initMap()
      })
    },
    //坐标拾取器回调方法
    selectLocation(e) {
      this.form.longitude = e.lng
      this.form.latitude = e.lat
      this.locationDialog = false
    },
    cancel() {
      this.reset()
      this.show = false
    },
    //表单提交
    handleSubmitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.estateId) {
            editEstate(this.form).then((response) => {
              this.$modal.msgSuccess('编辑成功')
              this.show = false
              this.$emit('success')
            })
          } else {
            addEstate(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.show = false
              this.$emit('success')
            })
          }
        }
      })
    }, 1000, true) //防抖
  }
}
</script>


<style scoped lang="scss">

</style>
